<template>
  <div class="prompt-list-container">
    <div class="prompt-header">
      <h1>提示词库</h1>
      <div class="prompt-actions">
        <a-button type="primary" @click="router.push('/prompts/create')" v-if="isLoggedIn">
          <template #icon><plus-outlined /></template>
          创建提示词
        </a-button>
      </div>
    </div>

    <div class="prompt-filters">
      <a-row :gutter="[16, 16]">
        <a-col :xs="24" :sm="24" :md="8">
          <a-input-search
            v-model:value="filters.search"
            placeholder="搜索提示词..."
            @search="handleSearch"
            allow-clear
          />
        </a-col>
        <a-col :xs="24" :sm="12" :md="6">
          <a-select
            v-model:value="filters.aiModel"
            placeholder="选择AI模型"
            style="width: 100%"
            allow-clear
            @change="handleFiltersChange"
          >
            <a-select-option v-for="model in aiModels" :key="model.id" :value="model.id">
              {{ model.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="12" :md="6">
          <a-select
            v-model:value="filters.tags"
            mode="multiple"
            placeholder="选择标签"
            style="width: 100%"
            allow-clear
            @change="handleFiltersChange"
          >
            <a-select-option v-for="tag in tags" :key="tag.id" :value="tag.id">
              {{ tag.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :xs="24" :sm="12" :md="4">
          <a-select
            v-model:value="filters.sort"
            placeholder="排序方式"
            style="width: 100%"
            @change="handleFiltersChange"
          >
            <a-select-option value="-created_at">最新创建</a-select-option>
            <a-select-option value="-updated_at">最近更新</a-select-option>
            <a-select-option value="-view_count">最多浏览</a-select-option>
            <a-select-option value="title">标题 A-Z</a-select-option>
          </a-select>
        </a-col>
      </a-row>
    </div>

    <a-spin :spinning="loading">
      <div v-if="prompts.length > 0" class="prompt-grid">
        <a-card
          v-for="prompt in prompts"
          :key="prompt.id"
          class="prompt-card"
          hoverable
          @click="viewPromptDetail(prompt.id)"
        >
          <template #title>
            <div class="prompt-title">{{ prompt.title }}</div>
          </template>
          <template #extra>
            <a-dropdown v-if="isOwner(prompt)" :trigger="['click']" @click.stop>
              <template #overlay>
                <a-menu>
                  <a-menu-item key="edit" @click.stop="editPrompt(prompt.id)">
                    <EditOutlined /> 编辑
                  </a-menu-item>
                  <a-menu-item key="copy" @click.stop="copyPrompt(prompt.id)">
                    <CopyOutlined /> 复制
                  </a-menu-item>
                  <a-menu-item key="delete" @click.stop="confirmDelete(prompt.id)">
                    <DeleteOutlined /> 删除
                  </a-menu-item>
                </a-menu>
              </template>
              <a-button type="text" @click.stop>
                <MoreOutlined />
              </a-button>
            </a-dropdown>
            <a-button v-else type="text" @click.stop="copyPrompt(prompt.id)">
              <CopyOutlined />
            </a-button>
          </template>
          <div class="prompt-description">{{ prompt.description }}</div>
          <div class="prompt-meta">
            <div class="prompt-tags">
              <a-tag v-for="tag in prompt.tags" :key="tag.id" color="blue" @click.stop>
                {{ tag.name }}
              </a-tag>
            </div>
            <div class="prompt-info">
              <span><EyeOutlined /> {{ prompt.view_count }}</span>
              <span><UserOutlined /> {{ prompt.user.username }}</span>
              <span><ClockCircleOutlined /> {{ formatDate(prompt.updated_at) }}</span>
            </div>
          </div>
        </a-card>
      </div>
      <a-empty v-else description="暂无提示词" />
    </a-spin>

    <div class="pagination-container">
      <a-pagination
        v-if="totalPrompts > 0"
        v-model:current="currentPage"
        :total="totalPrompts"
        :pageSize="pageSize"
        @change="handlePageChange"
        show-size-changer
        :pageSizeOptions="['10', '20', '50']"
        @showSizeChange="handleSizeChange"
      />
    </div>

    <a-modal
      v-model:visible="deleteModalVisible"
      title="删除提示词"
      @ok="handleDelete"
      @cancel="deleteModalVisible = false"
      okText="删除"
      cancelText="取消"
      :okButtonProps="{ danger: true }"
    >
      <p>确定要删除这个提示词吗？此操作无法撤销。</p>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { 
  PlusOutlined, EditOutlined, DeleteOutlined, 
  CopyOutlined, MoreOutlined, EyeOutlined,
  UserOutlined, ClockCircleOutlined
} from '@ant-design/icons-vue';
import { usePromptStore } from '../store/prompt';
import { useAuthStore } from '../store/auth';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';



const router = useRouter();
const promptStore = usePromptStore();
const authStore = useAuthStore();

const prompts = ref([]);
const tags = ref([]);
const aiModels = ref([]);
const loading = ref(false);
const totalPrompts = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const deleteModalVisible = ref(false);
const promptToDelete = ref(null);

const filters = reactive({
  search: '',
  tags: [],
  aiModel: null,
  sort: '-updated_at'
});

const isLoggedIn = computed(() => authStore.isAuthenticated);
const currentUser = computed(() => authStore.user);
    
    const isOwner = (prompt) => {
      return currentUser.value && prompt.user.id === currentUser.value.id;
    };
    
    const loadPrompts = async () => {
      loading.value = true;
      try {
        const params = {
          page: currentPage.value,
          page_size: pageSize.value,
          ...filters
        };
        
        const response = await promptStore.fetchPrompts(params);
        prompts.value = response.results || [];
        totalPrompts.value = response.count || 0;
      } catch (error) {
        message.error('获取提示词列表失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    const loadTags = async () => {
      try {
        const response = await promptStore.fetchTags();
        tags.value = response;
      } catch (error) {
        console.error('获取标签列表失败:', error);
      }
    };
    
    const loadAIModels = async () => {
      try {
        const response = await promptStore.fetchAIModels();
        aiModels.value = response;
      } catch (error) {
        console.error('获取AI模型列表失败:', error);
      }
    };
    
    const handleSearch = () => {
      currentPage.value = 1;
      loadPrompts();
    };
    
    const handleFiltersChange = () => {
      currentPage.value = 1;
      loadPrompts();
    };
    
    const handlePageChange = (page) => {
      currentPage.value = page;
      loadPrompts();
    };
    
    const handleSizeChange = (current, size) => {
      pageSize.value = size;
      currentPage.value = 1;
      loadPrompts();
    };
    
    const viewPromptDetail = (id) => {
      router.push(`/prompts/${id}`);
    };
    
    const editPrompt = (id) => {
      router.push(`/prompts/${id}/edit`);
    };
    
    const copyPrompt = async (id) => {
      try {
        await promptStore.copyExistingPrompt(id);
        message.success('提示词复制成功');
        loadPrompts();
      } catch (error) {
        message.error('复制提示词失败');
        console.error(error);
      }
    };
    
    const confirmDelete = (id) => {
      promptToDelete.value = id;
      deleteModalVisible.value = true;
    };
    
    const handleDelete = async () => {
      if (!promptToDelete.value) return;
      
      try {
        await promptStore.removePrompt(promptToDelete.value);
        message.success('提示词删除成功');
        deleteModalVisible.value = false;
        loadPrompts();
      } catch (error) {
        message.error('删除提示词失败');
        console.error(error);
      }
    };
    
    const formatDate = (dateString) => {
      try {
        return formatDistanceToNow(new Date(dateString), { 
          addSuffix: true,
          locale: zhCN
        });
      } catch (e) {
        return dateString;
      }
    };
    
    onMounted(() => {
      loadPrompts();
      loadTags();
      loadAIModels();
    });
</script>

<style scoped>
.prompt-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1rem;
}

.prompt-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.prompt-filters {
  margin-bottom: 2rem;
}

.prompt-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.prompt-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.prompt-title {
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.prompt-description {
  color: rgba(0, 0, 0, 0.65);
  margin-bottom: 1rem;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  flex-grow: 1;
}

.prompt-meta {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.prompt-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.prompt-info {
  display: flex;
  justify-content: space-between;
  color: rgba(0, 0, 0, 0.45);
  font-size: 0.85rem;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .prompt-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .prompt-grid {
    grid-template-columns: 1fr;
  }
}
</style>